# ========= 导入必要模块 ==========
import asyncio

import httpx
from ncatbot.core import BotClient, GroupMessage, PrivateMessage, RequestEvent
from ncatbot.utils import get_log
import random

token = ''

# ========== 创建 BotClient ==========
bot = BotClient()
_log = get_log()



# =====  权限验证工具，勿动 =====
def check_qq_in_group(qq, group: object = 1019241490, method_name=''):
    _log.info('调取私人信息喵，看看是不是微服群里的喵')
    data = {'token': token,
            'operator': qq,
            'qq': qq,
            'qg': group,
            'method_name': method_name}
    p = httpx.post("http://localhost:8000/bind/check_qq_in_group", data=data)
    _log.info(p.text)
    if p.status_code not in [0,200]:
        _log.info('不妙了喵，后端挂了喵')
        return False
    if p.json()['code'] != 0:
        return False
    return True

# ===== 测试后端通讯状况，仅测试群可用 =====
@bot.group_event()
async def on_group_message(msg: GroupMessage):
    _log.info(msg)
    ms =  msg.raw_message
    allowed_chars = ['喵'  ,'呜'  ,'哈',  '~'  ,'!',  '！',  '?',  '？',  '。',  '，',  ',',  '.',  '~'  ,]
    for i in ms:
        if i not in allowed_chars:
            return
    txt =  ms.count('喵')*'喵'
    if ms.count('呜')>0:
        txt = txt + '呜'
    if ms.count('!') > 0 or ms.count('！') > 0:
        txt = txt + '！'
    if ms.count('?') > 0 or ms.count('？') > 0:
        txt = txt + '？'

    if ms.count('喵') >0 and ms.count('呜')>0 and ms.count('~')>0:
        txt = '喵呜~'
    if ms.count('喵') >0 and ms.count('呜')>0 and (ms.count('?')or ms.count('？'))>0:
        txt = '喵呜？'
    if ms == '喵~':
        txt = '你好喵~'
    if ms.count('哈') >0 and ms.count('哈')/len(ms)>=0.25:
        txt = '哈'+ random.randint(2, 5)*'！'
    if ms.count('喵')/len(ms)>=0.7:
        if random.randint(0, 100)*ms.count('喵')/len(ms) >= 70:
            txt = '喵？你懂我家乡话喵？'
    if len(ms)>=15:
        if random.randint(0+len(ms), 100+len(ms)) >= 75:
            txt = '喵！你废话真多喵'
    #    await client.setGroupMute(ev.group_id, member.user_id, 60)
    await asyncio.sleep(random.randint(1, 3)/2)
    await msg.reply(text=txt)
@bot.group_event()
async def on_group_message(msg: GroupMessage):
    if msg.raw_message in ["后端活着吗？",'活着？','huozhe？','huozhe?'] and (msg.group_id == "468855960"):
        r =  httpx.post("http://localhost:8000/bind/check_alive")
        if  r.status_code in [0,200]:
            await msg.reply(text="活着喵~有什么事喵？")
        else:
            await msg.reply(text="后端？似了喵~")
# ===== 管理员使用的拉黑功能，保留 =====
@bot.group_event()
async def on_1(msg: GroupMessage):
    if msg.group_id != "925752891" and msg.group_id != "468855960":
        return
    # 拉黑 123 [原因]
    if msg.raw_message.startswith("拉黑 "):
        parts = msg.raw_message.split(" ", 3)
        if len(parts) < 2:
            await msg.reply("格式错误喵~\n正确格式：拉黑 QQ [原因]")
            return
        qq = parts[1]
        data = {'qq': qq, 'operator': msg.sender.user_id}
        if len(parts) >= 3:
            data.update({'reason': parts[2]})
        else:
            data.update({'reason': '无理由'})
        r = httpx.post("http://localhost:8000/qq/black_add_qq", data=data)
        if r.status_code != 200:
            j = r.json()
            if j['code'] == 0:
                await msg.reply(f"{j['msg']}")
            else:
                await msg.reply(f"拉黑失败喵~ 错误信息: {j['msg']}")
        data = {'qq': qq, 'operator': msg.sender.user_id}
        httpx.post("http://localhost:8000/bind/delete_bound", data=data)
# ===== 管理员使用的解封功能，保留 =====
@bot.group_event()
async def on_1(msg: GroupMessage):
    if msg.group_id != "925752891" and msg.group_id != "468855960":
        return
    if msg.raw_message.startswith("解封 "):
        parts = msg.raw_message.split(" ", 3)
        if len(parts) < 2:
            await msg.reply("格式错误喵~\n正确格式：解封 QQ")
            return
        qq = parts[1]
        data = {'qq': qq, 'operator': msg.sender.user_id}
        if len(parts) >= 3:
            data.update({'reason': parts[2]})
        else:
            data.update({'reason': '无理由'})
        r = httpx.post("http://localhost:8000/qq/black_delete_qq", data=data)
        if r.status_code != 200:
            j = r.json()
            if j['code']==0:
                await msg.reply(str(j['msg']))
            else:
                await msg.reply('非预期错误')
                _log.info(f"有人尝试使用解封功能，但出现了非预期的错误，错误信息：{j['msg']}")
# ===== 微笑写的自动拒绝与自动通过加群申请，保留 =====
@bot.request_event()
async def on_request(msg: RequestEvent):
    if msg.request_type != "group":
        return
    res = await bot.api.get_stranger_info(msg.user_id)
    data = {'token': token, 'operator': 202704485, 'qq': msg.user_id}
    r = httpx.post("http://localhost:8000/qq/check_qq_in_black", data=data)
    if r.status_code == 200:
        j = r.json()
        if j['data']['state'] == 1:
            await msg.approve(False, reason=f"抱歉，您已被拉黑，已被自动拒绝喵~")
            await bot.api.post_group_msg(group_id=msg.group_id,
                                         text=f"用户“{res['data']['nickname']}” 处于黑名单中，已被自动拒绝进群喵~")
            return
    if res['status'] == 'ok' and res['data']['qqLevel'] < 8:
        await msg.approve(False, reason="抱歉，您的QQ等级不足8级，已被自动拒绝喵~")
        await bot.api.post_group_msg(group_id=msg.group_id,
                                     text=f"用户“{res['data']['nickname']}”的QQ等级为{res['data']['qqLevel']}，已被自动拒绝进群喵~")
    if res['status'] == 'ok' and res['data']['qqLevel'] >= 48:
        await msg.approve(True)
        await bot.api.post_group_msg(group_id=msg.group_id,
                                     text=f"用户“{res['data']['nickname']}”的QQ等级为{res['data']['qqLevel']}，已被自动批准进群喵~")
# ===== ===== ===== 以下为新后端代码 ===== ===== =====
# ===== 玩家私聊获取帮助 =====
@bot.private_event()
async def on_private_message(msg: PrivateMessage):
    _log.info(msg)
    if not msg.raw_message == '帮助':
        return
    _log.info('有人查帮助喵？该不该回复喵？')
    msga = "喵~这里是帮助喵"
    msga = msga + "\n#绑定 123abc  绑定你的IP喵~，如果需要绑定新IP需要再次通过网页获得新的绑定码的喵~"
    msga = msga + "\n查绑定  查询你绑定的IP的喵~"
    msga = msga + "\n解除绑定 123  按序号解除你绑定的IP喵~序号是通过查绑定获得的喵~"
    msga = msga + "\n最多同时绑定3个IP喵~绑定新IP需要先解除旧的喵~"
    if check_qq_in_group(msg.user_id, 1019241490, '帮助'):
        await msg.reply(msga)
        return
    else:
        return
        #先不启用群外人员私聊提醒，看情况
        # await msg.reply("抱歉喵~\n你不是微服群的成员，无法使用绑定功能喵~\n请先加入微服群1019241490喵~")
# ===== 管理员在管理群获取帮助 =====
@bot.group_event()
async def on_1(msg: GroupMessage):
    if msg.group_id in ["925752891", "468855960"]:
        msgb = "喵~这里是帮助喵"
        msgb = msgb + "\n#绑定 123abc  绑定你的IP喵~，如果需要绑定新IP需要再次通过网页获得新的绑定码的喵~"
        msgb = msgb + "\n查绑定  查询你绑定的IP的喵~"
        msgb = msgb + "\n解除绑定 123  按序号解除你绑定的IP喵~解除前先用“查绑定”看一下喵~"
        msgb = msgb + "\n最多同时绑定3个IP喵~绑定新IP需要先解除旧的喵~"
        msgb = msgb + "\n管理员可以使用“管理员帮助”查看管理员的帮助喵~"
        # ===== 以上是普通玩家的帮助，以下是管理员的帮助 =====
        msgc = "管理员帮助喵~"
        msgc = msgc + "\n拉黑 123456  拉黑一个用户喵~"
        msgc = msgc + "\n解封 123456  解封一个用户喵~"
        msgc = msgc + "\n查黑 123456  查询一个用户是否在黑名单中喵~"
        msgc = msgc + "\n查QQ绑定 123456  查询QQ号绑定情况喵~"
        msgc = msgc + "\n查IP绑定 192.168.0.1  查询IP绑定情况喵~"

        if msg.raw_message == '帮助':
            await msg.reply(msgb)
        if msg.raw_message == '管理员帮助':
            await msg.reply(msgc)
# ===== 绑定，需要先通过网页获取绑定码 =====
@bot.private_event()
async def on_private_message(msg: PrivateMessage):
    if not msg.raw_message.startswith('#绑定'):
        return
    _log.info('有人要绑定喵')
    parts = msg.raw_message.split(" ", 1)
    if len(parts) != 2:
        await msg.reply("格式错误喵~\n正确格式：#绑定 123abc")
        return
    bind_code = parts[1]
    # 如果 bind_code 不是数字和字母的组合，返回错误
    if not bind_code.isalnum():
        await msg.reply("格式错误喵~\n正确格式：#绑定 123abc，是数字和字母的组合喵~")
        return
    qq = int(msg.sender.user_id)
    if not check_qq_in_group(qq, 1019241490, '#绑定'):
        return
    data = {'token': token,
            'operator': int(msg.sender.user_id),
            'qq': qq,
            'bind_code': bind_code}
    r = httpx.post("http://localhost:8000/bind/bind_qq", data=data)
    _log.info('好像有结果了喵')
    if r.status_code != 200:
        await msg.reply(f"网络错误喵~ 请稍后再试喵~")
        return
    t = r.json()
    _log.info('处理中喵喵')
    if t['code'] == 0:
        await msg.reply(t['msg'])
        return
    if t['code'] != 0:
        _log.info('快来看看喵~非预期的返回喵：\n' + str(t))
    await msg.reply('喵~绑定成功了喵~最多可以绑定3个IP喵~，说“帮助”获得更多帮助喵~')
# ===== 此功能使用户可以通过私聊查自己的绑定信息 =====
@bot.private_event()
async def on_private_message(msg: PrivateMessage):
    if msg.raw_message != '查绑定':
        return
    _log.info('有人在查绑定喵')
    qq = int(msg.sender.user_id)
    if not check_qq_in_group(qq, 1019241490, '查绑定'):
        return
    data = {
        'operator': qq,
        'qq': qq,
    }
    print(data)
    r = httpx.post("http://localhost:8000/bind/check_bound_qq", data=data)
    if r.status_code != 200 :
        await msg.reply(f"网络错误喵~ 请稍后再试喵~")
        return
    x2 = r.json()
    if x2['code'] != 0:
        await msg.reply('查询结果出来了喵~' + str(x2['msg']))
        return
    print(x2)
    if (x2['data']) is None or len(x2['data']) == 0:
        await msg.reply(f'查询结果出来了喵~没有有效的绑定信息喵~')
        return
    d = x2['data']
    if len(d) == 0:
        await msg.reply(f'查询结果出来了喵~没有有效的绑定信息喵~')
        return
    if len(d) >= 1:
        msga = str(d[0]['qq']) + "绑定的IP有：\n"
        msga = str(msga) + '1. [' + str(d[0]['ip']) + '][' + str(d[0]['bound_time'])+']'
        if len(d) >= 2:
            msga = str(msga)+'\n' + '2. [' + str(d[1]['ip']) +']['+ str(d[1]['bound_time'])+']'
        if len(d) >= 3:
            msga = str(msga)+'\n' + '3. [' + str(d[2]['ip']) + '][' + str(d[2]['bound_time'])+']'
        await msg.reply(f"查询有结果了喵~{msga}")
# ===== 查指定对象绑定信息,管理群专用 =====
@bot.group_event()
async def on_group_message(msg: GroupMessage):
    if msg.raw_message.startswith('查QQ') == False and msg.raw_message.startswith('查qq') == False:
        return
    _log.info('喵~有人在查指定QQ绑定喵')
    if int(msg.group_id) not in [925752891, 468855960]:
        return
    if msg.raw_message == '查QQ绑定':
        await msg.reply("格式错误喵~\n正确格式：查QQ绑定 1234567")
        return
    if msg.raw_message == '查IP绑定':
        await msg.reply("格式错误喵~\n正确格式：查QQ绑定 0.0.0.0")

    parts = msg.raw_message.split(" ", 2)
    if len(parts) != 2:
        await msg.reply("格式错误喵~\n正确格式：查QQ绑定 1234567 或 查IP绑定 192.168.0.1")
        return
    _log.info('qq号为' + str(msg.sender.user_id) + '的用户正在查询qq' + str(parts[1]) + '喵')  # 目前只让加入微服的人访问
    data = {'token': '', 'operator': int(msg.sender.user_id), 'qq': parts[1]}
    r2 = httpx.post("http://localhost:8000/bind/check_bound_qq", data=data)
    if r2.status_code != 200:
        await msg.reply('查询失败喵~' + '发生了非预期的错误')
        return
    x2 = r2.json()
    if x2['code'] !=0:
        await msg.reply('查询结果出来了喵~' + str(x2['msg']))
        return
    print(x2)
    if (x2['data']) is None or len(x2['data']) == 0:
        await msg.reply(f'查询结果出来了喵~没有有效的绑定信息喵~')
        return
    d = x2['data']
    if len(d) == 0:
        await msg.reply(f'查询结果出来了喵~没有有效的绑定信息喵~')
        return
    if len(d) >= 1:
        msga = str(d[0]['qq']) + "绑定的IP有：\n"
        msga = str(msga) + '1. [' + str(d[0]['ip']) + '][' + str(d[0]['bound_time']) + ']'
        if len(d) >= 2:
            msga = str(msga) + '\n' + '2. [' + str(d[1]['ip']) + '][' + str(d[1]['bound_time']) + ']'
        if len(d) >= 3:
            msga = str(msga) + '\n' + '3. [' + str(d[2]['ip']) + '][' + str(d[2]['bound_time']) + ']'
        await msg.reply(f"查询有结果了喵~{msga}")
# ===== 查指定IP绑定信息,管理群专用 =====
@bot.group_event()
async def on_group_message(msg: GroupMessage):
    if msg.raw_message.startswith('查IP') == False and msg.raw_message.startswith('查ip') == False:
        return
    _log.info('喵~有人在查指定IP绑定喵')
    if int(msg.group_id) not in [925752891, 468855960]:
        return
    if msg.raw_message == '查IP绑定'or'查ip绑定':
        await msg.reply("喵~\n格式示例：查IP绑定 192.168.0.1 或 查ip绑定 192.168.0.1")
        return
    parts = msg.raw_message.split(" ", 2)
    if len(parts) != 2:
        await msg.reply("喵~\n格式示例：查IP绑定 192.168.0.1 或 查ip绑定 192.168.0.1")
        return
    _log.info('qq号为' + str(msg.sender.user_id) + '的用户正在查询ip' + str(parts[1]) + '喵')
    data = {'token': '', 'operator': int(msg.sender.user_id), 'ip': parts[1]}
    r2 = httpx.post('http://localhost:8000/bind/check_bound_ip', data=data)
    if r2.status_code != 200:
        await msg.reply('查询失败喵~' + '发生了非预期的错误')
        return
    x2 = r2.json()
    if x2['code'] != 0:
        await msg.reply('查询结果出来了喵~' + str(x2['msg']))
        return
    print(x2)
    if (x2['data']) is None or len(x2['data']) == 0:
        await msg.reply(f'查询结果出来了喵~没有有效的绑定信息喵~')
        return
    d = x2['data']
    if len(d) == 0:
        await msg.reply(f'查询结果出来了喵~没有有效的绑定信息喵~')
        return
    if len(d) >= 1:
        ##重做ing
        msga = str(d[0]['qq']) + "绑定的IP有：\n"
        msga = str(msga) + '1. [' + str(d[0]['ip']) + '][' + str(d[0]['bound_time']) + ']'
        if len(d) >= 2:
            msga = str(msga) + '\n' + '2. [' + str(d[1]['ip']) + '][' + str(d[1]['bound_time']) + ']'
        if len(d) >= 3:
            msga = str(msga) + '\n' + '3. [' + str(d[2]['ip']) + '][' + str(d[2]['bound_time']) + ']'
        await msg.reply(f"查询有结果了喵~{msga}")
# ===== 私聊解除绑定，必须是私聊，必须加微服群 =====
@bot.private_event()
async def on_private_message(msg: PrivateMessage):
    if not msg.raw_message.startswith('解除绑定'):
        return
    qq = int(msg.sender.user_id)
    if not check_qq_in_group(qq, 1019241490, '解除绑定', ):
        return
    data = {
        'token': '',
        'operator': msg.sender.user_id,
        'qq': msg.sender.user_id,
    }
    r = httpx.post("http://localhost:8000/bind/delete_bound", data=data)
    if r.status_code != 200:
        p = r.json()
        if p == {}:
            await msg.reply("坏了喵~后端传回来空数据喵~")
            return
        if p['code'] != 0:
            await msg.reply("坏了喵~后端说" + str(p['code']) + str(p['msg']))
            return
    await msg.reply(f"发来贺电喵~解除绑定成功喵~")




# ========== 启动 BotClient==========
if __name__ == "__main__":
    bot.run()  # 这里写 Bot 的 QQ 号
